using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PasteFormHelper;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace OpenPasteSpider.projectmodel
{

    /// <summary>
    /// 总任务概述
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
    public class PlanInfoAppService : OpenPasteSpiderAppService
    {

        private IOpenPasteSpiderDbContext _dbContext;
        public PlanInfoAppService(IOpenPasteSpiderDbContext dbContext)
        {
            _dbContext = dbContext;
        }



        /// <summary>
        /// 读取任务列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PagedResultDto<PlanInfoListDto>> GetListAsync(InputSearchPlan input)
        {

            //哪一个服务器的 哪一个项目的 什么状态 

            var _querytotal = _dbContext.PlanInfo.Where(t => 1 == 1)
                .WhereIf(input.projectid != 0, x => x.ProjectId == input.projectid)
                .WhereIf(input.state != RunState.unknow, x => x.State == input.state)
                .WhereIf(input.linuxid != 0, x => x.LinuxId == input.linuxid);
            var pagedResultDto = new PagedResultDto<PlanInfoListDto>();
            pagedResultDto.TotalCount = await _querytotal.CountAsync();

            if (pagedResultDto.TotalCount > 0)
            {
                var query = await (from a in _querytotal
                                   join linux in _dbContext.LinuxInfo on a.LinuxId equals linux.Id into li
                                   from l in li.DefaultIfEmpty()
                                   join service in _dbContext.ServiceInfo on a.ServiceId equals service.Id into si
                                   from s in si.DefaultIfEmpty()
                                   join model in _dbContext.ModelInfo on a.ModelId equals model.Id into mo
                                   from m in mo.DefaultIfEmpty()
                                   select new PlanInfoListDto
                                   {
                                       Id = a.Id,
                                       AppId = a.AppId,
                                       CreateDate = a.CreateDate,
                                       Durtion = a.Durtion,
                                       LinuxId = a.LinuxId,
                                       ModelId = a.ModelId,
                                       NginxId = a.NginxId,
                                       OrderModel = a.OrderModel,
                                       ProjectId = a.ProjectId,
                                       ServiceId = a.ServiceId,
                                       State = a.State,
                                       StoreId = a.StoreId,
                                       Version = a.Version,
                                       LinuxName = l != null ? l.Name : "",
                                       ServiceName = s != null ? s.Name : "",
                                       StoreName = "",
                                       ModelCode = m != null ? m.Code : ""
                                   }).OrderByDescending(x => x.Id).Page(input.page, input.size).ToListAsync();
                pagedResultDto.Items = query;
            }
            else
            {
                throw new PasteCodeException("没有查询到数据！", CodeLevel.ShowInfo);
            }



            return pagedResultDto;
        }

        /// <summary>
        /// 根据ID获取单项总任务概述
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public PlanInfoDto GetByIdAsync(int id)
        {
            var query = _dbContext.PlanInfo.Where(t => t.Id == id).FirstOrDefault();
            var temList = ObjectMapper.Map<PlanInfo, PlanInfoDto>(query);
            return temList;
        }

        ///// <summary>
        ///// 读取AddDto的数据模型 用于新增
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //[TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        //public VoloModelInfo ReadAddModel()
        //{
        //    var _model = PasteBuilderHelper.ReadModelProperty<PlanInfoAddDto>(new PlanInfoAddDto());
        //    return _model;
        //}

        ///// <summary>
        ///// 读取Dto的数据模型 用于更新
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //[TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        //public async Task<VoloModelInfo> ReadUpdateModel(int id)
        //{
        //    var _info = await _dbContext.PlanInfo.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
        //    if (_info == null || _info == default)
        //    {
        //        throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
        //    }
        //    var dto = ObjectMapper.Map<PlanInfo, PlanInfoUpdateDto>(_info);
        //    var _dataModel = PasteBuilderHelper.ReadModelProperty<PlanInfoUpdateDto>(dto);
        //    return _dataModel;
        //}

        /// <summary>
        /// 读取Dto的数据模型 用于查看详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<VoloModelInfo> ReadDetailModel(int id)
        {
            var _info = await _dbContext.PlanInfo.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_info == null || _info == default)
            {
                throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
            }
            var dto = ObjectMapper.Map<PlanInfo, PlanInfoDto>(_info);
            var _dataModel = PasteBuilderHelper.ReadModelProperty<PlanInfoDto>(dto);
            return _dataModel;
        }

        /// <summary>
        /// 读取ListDto的数据模型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public VoloModelInfo ReadListModel()
        {
            var _model = PasteBuilderHelper.ReadModelProperty<PlanInfoListDto>(new PlanInfoListDto());
            var _query_model = PasteBuilderHelper.ReadModelProperty(new InputSearchBase());
            if (_query_model != null)
            {
                _model.QueryProperties = _query_model.Properties;
            }
            return _model;
        }

        /// <summary>
        /// 按页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<PagedResultDto<PlanInfoListDto>> Page([FromQuery] InputSearchBase input)
        {
            var query = _dbContext.PlanInfo.Where(t => 1 == 1).OrderByDescending(x => x.Id);
            var _pagedto = new PagedResultDto<PlanInfoListDto>();
            _pagedto.TotalCount = await query.CountAsync();
            var userList = await query.Page(input.page, input.size).ToListAsync();
            var temList = ObjectMapper.Map<List<PlanInfo>, List<PlanInfoListDto>>(userList);
            _pagedto.Items = temList;
            return _pagedto;
        }
        ///// <summary>
        ///// 根据ID获取待更新单项信息总任务概述
        /////</summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public PlanInfoUpdateDto GetInfoForUpdateAsync(int id)
        //{
        //    var query = _dbContext.PlanInfo.Where(t => t.Id == id)
        //    .FirstOrDefault();
        //    var temList = ObjectMapper.Map<PlanInfo, PlanInfoUpdateDto>(query);
        //    return temList;
        //}


        ///// <summary>
        ///// 添加一个总任务概述
        /////</summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<PlanInfoDto> CreateItemAsync(PlanInfoAddDto input)
        //{

        //    var newu = ObjectMapper.Map<PlanInfoAddDto, PlanInfo>(input);
        //    newu.CreateDate = DateTime.Now;            //添加自定义
        //    _dbContext.Add(newu);
        //    await _dbContext.SaveChangesAsync();
        //    //var updated = await _repository.InsertAsync(newu,true);
        //    var backinfo = ObjectMapper.Map<PlanInfo, PlanInfoDto>(newu);
        //    return backinfo;
        //}
        ///// <summary>
        ///// 更新一个总任务概述
        /////</summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<PlanInfoDto> UpdateItemAsync(PlanInfoUpdateDto input)
        //{
        //    var info = await _dbContext.PlanInfo.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
        //    if (info == null || info == default)
        //    {
        //        throw new UserFriendlyException("需要查询的信息不存在", "404");
        //    }
        //    ObjectMapper.Map<PlanInfoUpdateDto, PlanInfo>(input, info);
        //    //var updated = await _repository.UpdateAsync(newu);
        //    await _dbContext.SaveChangesAsync();
        //    var backinfo = ObjectMapper.Map<PlanInfo, PlanInfoDto>(info);
        //    return backinfo;
        //}
    }
}
